import React, { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { useDispatch, useSelector } from '../../../store/hooks'
import { 
  fetchRegistrationOrders, 
  cancelRegistrationOrder,
  selectRegistrationOrders,
  selectOrdersLoading,
  selectOrdersError
} from '../../../store/slices/ordersSlice'
import TopNavbar from '../../../components/TopNavbar'
import ErrorBoundary from '../../../components/ErrorBoundary'
import styles from './index.module.css'

const RegistrationOrders = () => {
  const navigate = useNavigate()
  const dispatch = useDispatch()
  
  // 从Redux store获取数据
  const orders = useSelector(selectRegistrationOrders)
  const loading = useSelector(selectOrdersLoading)
  const error = useSelector(selectOrdersError)

  useEffect(() => {
    // 获取挂号订单数据
    dispatch(fetchRegistrationOrders())
  }, [dispatch])

  const getStatusColor = (status) => {
    switch (status) {
      case '已完成':
        return '#52c41a'
      case '待就诊':
        return '#1890ff'
      case '已取消':
        return '#ff4d4f'
      default:
        return '#666'
    }
  }

  const getStatusIcon = (status) => {
    switch (status) {
      case '已完成':
        return '✅'
      case '待就诊':
        return '⏰'
      case '已取消':
        return '❌'
      default:
        return '❓'
    }
  }

  const handleOrderDetail = (order) => {
    // 跳转到订单详情页面
    console.log('查看订单详情:', order)
    // 这里可以跳转到订单详情页面
  }

  const handleCancelOrder = async (order) => {
    if (order.status === '待就诊') {
      try {
        await dispatch(cancelRegistrationOrder(order.id)).unwrap()
        alert('订单取消成功')
      } catch (error) {
        console.error('取消订单失败:', error)
        alert('取消订单失败，请稍后重试')
      }
    }
  }

  if (loading) {
    return (
      <div className={styles.ordersPage}>
        <ErrorBoundary>
          <TopNavbar
            title="挂号订单"
            showBack={true}
            onBack={() => navigate(-1)}
          />
        </ErrorBoundary>
        <div className={styles.loadingContainer}>
          <div className={styles.loadingSpinner}></div>
          <div className={styles.loadingText}>加载中...</div>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className={styles.ordersPage}>
        <ErrorBoundary>
          <TopNavbar
            title="挂号订单"
            showBack={true}
            onBack={() => navigate(-1)}
          />
        </ErrorBoundary>
        <div className={styles.content}>
          <div className={styles.errorState}>
            <div className={styles.errorIcon}>❌</div>
            <div className={styles.errorText}>加载失败</div>
            <div className={styles.errorSubtext}>{error}</div>
            <button 
              className={styles.retryBtn}
              onClick={() => dispatch(fetchRegistrationOrders())}
            >
              重试
            </button>
          </div>
        </div>
      </div>
    )
  }

  if (orders.length === 0) {
    return (
      <div className={styles.ordersPage}>
        <ErrorBoundary>
          <TopNavbar
            title="挂号订单"
            showBack={true}
            onBack={() => navigate(-1)}
          />
        </ErrorBoundary>
        <div className={styles.content}>
          <div className={styles.emptyState}>
            <div className={styles.emptyIcon}>📋</div>
            <div className={styles.emptyText}>暂无挂号订单</div>
            <div className={styles.emptySubtext}>您还没有挂号记录</div>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className={styles.ordersPage}>
      <ErrorBoundary>
        <TopNavbar
          title="挂号订单"
          showBack={true}
          onBack={() => navigate(-1)}
        />
      </ErrorBoundary>
      
      <div className={styles.content}>
        <div className={styles.ordersList}>
          {orders.map((order) => (
            <div key={order.id} className={styles.orderCard}>
              <div className={styles.orderHeader}>
                <div className={styles.orderId}>
                  订单号: {order.registrationNo}
                </div>
                <div 
                  className={styles.orderStatus}
                  style={{ color: getStatusColor(order.status) }}
                >
                  {getStatusIcon(order.status)} {order.status}
                </div>
              </div>
              
              <div className={styles.orderInfo}>
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>患者姓名:</span>
                  <span className={styles.infoValue}>{order.patientName}</span>
                </div>
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>科室:</span>
                  <span className={styles.infoValue}>{order.department}</span>
                </div>
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>医生:</span>
                  <span className={styles.infoValue}>{order.doctorName}</span>
                </div>
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>就诊日期:</span>
                  <span className={styles.infoValue}>{order.appointmentDate}</span>
                </div>
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>就诊时间:</span>
                  <span className={styles.infoValue}>{order.appointmentTime}</span>
                </div>
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>挂号费:</span>
                  <span className={styles.infoValue}>¥{order.fee}</span>
                </div>
                {order.symptoms && (
                  <div className={styles.infoRow}>
                    <span className={styles.infoLabel}>症状:</span>
                    <span className={styles.infoValue}>{order.symptoms}</span>
                  </div>
                )}
                {order.diagnosis && order.diagnosis !== '待诊断' && (
                  <div className={styles.infoRow}>
                    <span className={styles.infoLabel}>诊断:</span>
                    <span className={styles.infoValue}>{order.diagnosis}</span>
                  </div>
                )}
                {order.treatment && order.treatment !== '待治疗' && (
                  <div className={styles.infoRow}>
                    <span className={styles.infoLabel}>治疗:</span>
                    <span className={styles.infoValue}>{order.treatment}</span>
                  </div>
                )}
              </div>
              
              <div className={styles.orderActions}>
                <button 
                  className={styles.actionBtn}
                  onClick={() => handleOrderDetail(order)}
                >
                  查看详情
                </button>
                {order.status === '待就诊' && (
                  <button 
                    className={`${styles.actionBtn} ${styles.cancelBtn}`}
                    onClick={() => handleCancelOrder(order)}
                  >
                    取消预约
                  </button>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}

export default RegistrationOrders
